<?php
namespace app\merchant\controller;
use app\common\controller\CarddateTest;
use app\common\controller\CardsdateNew;
use app\common\controller\Helpinfo;
use app\common\controller\TestBase;
use app\common\model\CardCzgive;
use app\common\model\CardMember;
use app\common\model\CardType;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\CardConsume;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use app\common\model\System;
use app\common\controller\Carddate;
use app\common\controller\AdminBase;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
class Cardstest extends TestBase
{

    //首页列表
    public function cardslist(){
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['card_type'] != ''){
                $map['card_type'] = $p_data['card_type'];
            }
            if ($p_data['time_type'] != ''){
                $map['time_type'] = $p_data['time_type'];
            }
        } else {
            $p_data['card_type'] = '';
        }
        $top_mid = Session::get('login_top_mid');
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        }else{
            $map['top_mid'] = $top_mid;
        }
        $CardType = new CardType();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
//        $map['card_id'] = ['neq',null];
        $map['is_put'] = 1;
        $map['is_del'] = 1;
        $map['end_timestamp'] = ['GT',time()];
        $list = $CardGeneral->where($map)->order('create_time desc')->paginate(10);
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $card = $CardType->select();
        $this->assign('card',$card);
        $this->assign('mach',$mach);
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //草稿箱
    public function draftslist(){
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['card_type'] != ''){
                $map['card_type'] = $p_data['card_type'];
            }
        } else {
            $p_data['card_type'] = '';
        }
        $top_mid = Session::get('login_top_mid');
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        }else{
            $map['top_mid'] = $top_mid;
        }
        $CardType = new CardType();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $map['is_put'] = 0;
        $map['card_id'] = null;
        $list = $CardGeneral->where($map)->order('create_time desc')->paginate(10);
//        var_dump($CardGeneral->getLastSql());
//        var_dump($list);
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $card = $CardType->select();
        $this->assign('card',$card);
        $this->assign('mach',$mach);
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function overlist(){
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['card_type'] != ''){
                $map['card_type'] = $p_data['card_type'];
            }
        } else {
            $p_data['card_type'] = '';
        }
        $top_mid = Session::get('login_top_mid');
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        }else{
            $map['top_mid'] = $top_mid;
        }
        $CardType = new CardType();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
//        $map['card_id'] = ['neq',null];
        $map['is_put'] = 1;
        $map['end_timestamp'] = ['LT',time()];
        $list = $CardGeneral->where($map)->order('create_time desc')->paginate(10);
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $card = $CardType->select();
        $this->assign('card',$card);
        $this->assign('mach',$mach);
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //创建卡券
    public function creatcards(Request $request){
        if (Request()->isPost()){
            $param = $request->post();
            switch ($param['type']){
                case "getinfo":
                    $Merchant = new Merchant();
                    $Momerchant = new Momerchant();
                    $map['id'] = ['in', $this->get_mer_mid()];
                    $map['wx_open_id'] = ['neq',''];
                    $moinfo = $Momerchant->where(['id'=>Session::get('login_top_mid')])->field('img_wx,merchant_name,cust_call')->find();
                    $mach = $Merchant->where($map)->field('id,sub_mch_id,merchant')->find();
                    if ($moinfo && $mach){
                        $info['mid'] = $mach['id'];
                        $info['create_mid'] = $mach['sub_mch_id'];
                        $info['logo_url'] = $moinfo['img_wx'];
                        $info['brand_name'] = $moinfo['merchant_name'];
                        $info['base_info']['service_phone'] = $moinfo['cust_call'];
                        //END
                        $re_arr['return_code'] = 'SUCCESS';
                        $re_arr['return_msg'] = '成功';
                        $re_arr['info'] = $info;
                    }else{
                        $re_arr['return_code'] = 'FAIL';
                        $re_arr['return_msg'] = '失败';
                    }
                    break;
                case "createcards":
                    $CardGeneral = new CardGeneral();
                    $CardsdateNew = new CardsdateNew();
                    file_put_contents('/data2/html/payos/addcards.txt', '1:' . json_encode($param).PHP_EOL, FILE_APPEND);
                    $mid = $param['mid'];
                    if ($mid && $this->checkmid($mid)) {
                        if ($param['date_info'] == 'DATE_TYPE_FIX_TIME_RANGE') {
                            if (isset($param['times'])) {
                                $times = explode(" - ", $param['times']);
                                if ($times) {
                                    $param['begin_timestamp'] = $times[0];
                                    $param['end_timestamp'] = $times[1];
                                }
                            }
                        } else {
                            $param['begin_timestamp'] = '';
                        }
                        file_put_contents('/data2/html/payos/addcards.txt', '2:' . json_encode($param).PHP_EOL, FILE_APPEND);
                        $data = $CardsdateNew->creatcard($param, 1);
                        file_put_contents('/data2/html/payos/addcards.txt', '3:' . json_encode($param).PHP_EOL, FILE_APPEND);
                        $datas = $CardsdateNew->creatcard($param, 2);
                        file_put_contents('/data2/html/payos/addcards.txt', '4:' . json_encode($param).PHP_EOL, FILE_APPEND);
                        $datas['card_info'] = json_encode($data, JSON_UNESCAPED_UNICODE);
                        $conten = $CardGeneral->save($datas);
                        if ($conten !== false) {
                            $re_arr['return_code'] = 'SUCCESS';
                            $re_arr['return_msg'] = '成功';
                        } else {
                            $re_arr['return_code'] = 'FAIL';
                            $re_arr['return_msg'] = '失败';
                        }
                    }else{
                        $re_arr['return_code'] = 'FAIL';
                        $re_arr['return_msg'] = '失败';
                    }
                    break;
                default:
                    $re_arr['return_code'] = 'FAIL';
                    $re_arr['return_msg'] = '错误的方式';
                    break;
            }
            return json($re_arr);

        }else{
            $auth_type = $this->get_auth_type();
            if ($auth_type) {
                $param = $request->param();
                $this->assign('param',$param);
                return $this->fetch();
            }else{
                $this->success('请前往设置微信授权。','index/index');
            }
        }
    }


    //修改卡券草稿
    public function editdrafts(Request $request){
        $get_param = $request->param();
        if (isset($get_param['id']) ) {
            $id = $get_param['id'];
            $CardGeneral = new CardGeneral();
            $top_mid = Session::get('login_top_mid');
            $map['top_mid'] = ['in', $top_mid];
            $map['id'] = $id;
            $info = $CardGeneral->where($map)->find();
            if ($info) {
                if ($request->isAjax()) {
                    $param = $request->post();
                    switch ($param['type']){
                        case "getinfo":
                            $info['base_info'] = json_decode($info['base_info'], true);
                            $info['advanced_info'] = json_decode($info['advanced_info'], true);
                            if ($info['advanced_info']['abstract']['icon_url_list']) {
                                $info['icon_url_list'] = $info['advanced_info']['abstract']['icon_url_list'][0];
                            }else{
                                $info['icon_url_list'] = '';
                            }
                            //END
                            $re_arr['return_code'] = 'SUCCESS';
                            $re_arr['return_msg'] = '成功';
                            $re_arr['info'] = $info;
                            break;
                        case "editdrafts":
                            file_put_contents('/data2/html/payos/addcards.txt', '1:' . json_encode($param).PHP_EOL, FILE_APPEND);
                            $CardsdateNew = new CardsdateNew();
                            if ($param['date_info'] == 'DATE_TYPE_FIX_TIME_RANGE') {
                                if (isset($param['times'])) {
                                    $times = explode(" - ", $param['times']);
                                    if ($times) {
                                        $param['begin_timestamp'] = $times[0];
                                        $param['end_timestamp'] = $times[1];
                                    }
                                }
                            } else {
                                $param['begin_timestamp'] = '';
                            }
                            $data = $CardsdateNew->creatcard($param, 1);
                            $datas = $CardsdateNew->creatcard($param, 2);
                            $datas['card_info'] = json_encode($data, JSON_UNESCAPED_UNICODE);
                            $conten = $CardGeneral->save($datas, ['id' => $id]);
                            //END
                            if ($conten !== false) {
                                $re_arr['return_code'] = 'SUCCESS';
                                $re_arr['return_msg'] = '成功';
                            } else {
                                $re_arr['return_code'] = 'FAIL';
                                $re_arr['return_msg'] = '失败';
                            }
                            break;
                        default:
                            $re_arr['return_code'] = 'FAIL';
                            $re_arr['return_msg'] = '错误的方式';
                            break;
                    }
                    return json($re_arr);
                } else {
                    $param = $request->param();
                    $this->assign('param',$param);
                    return $this->fetch();
                }
            }else{
                $this->error('请修改属于您的卡券','cards/draftslist');
            }
        }else{
            $this->error('错误的方式','cards/draftslist');
        }
    }


    public function getmachlist()
    {
        if (Request()->isAjax()) {
            $Merchant = new Merchant();
            $map['id'] = array('in', $this->get_mer_mid());
            $list = $Merchant->where($map)->select();
            return json($list);
        }
    }

    //发布卡券
    public function putcards(){
        if (Request()->isGet()) {
            $id = request()->param('id');
            if ($id) {
                $map['id'] = $id;
                $map['top_mid'] = Session::get('login_top_mid');
                $CardGeneral = new CardGeneral();
                $info = $CardGeneral->where($map)->find();
                if ($info) {
                    //初始化微信API
                    $options = $this->option($info['mid']);
                    $wxObj = new Wxobjopen($options);
                    //向接口发送创建
                    $data = json_decode($info['card_info'], true);

                    $res = $wxObj->createUserCard($data);

                    if ($res['errcode'] == 0) {
                        $datas['card_id'] = $res['card_id'];
                        $datas['is_put'] = 1;
                        $CardGeneral->allowField(true)->save($datas, $map);
                        $this->success('发布成功');
                    } else {
                        //错误提示翻译
                        $Helpinfo = new Helpinfo();
                        $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                        //END
//                        var_dump($res);
                        $datas['errmsg'] = $errmsg;
                        $CardGeneral->allowField(true)->save($datas, $map);
                        $this->error('发布失败' . $errmsg, url('cards/editdrafts', $map), 15);
                    }
                }else{
                    $this->error('请发布属于您的卡券','cards/draftslist');
                }
            }
        }
    }

    //删除卡券
    public function delcards(Request $request){
        if ($request->isAjax()){
            $param = $request->post();
//            return json($param);
            $card_id = $param['card_id'];

            $CardGeneral = new CardGeneral();
            $CardUserGet = new CardUserGet();
            $CardConsum = new CardConsume();
            //初始化微信API
            $data['card_id'] = $card_id;
            $mid = $this->getmid($card_id);
            if ($this->checkmid($mid)) {
                $mab['statu'] = 0;
                $mab['card_id'] = $card_id;
                $mab['end_time'] = ['gt',time()];
                $ncuser = $CardUserGet->where($mab)->find();
                if (!$ncuser) {
                    $options = $this->option($mid);
                    $wxObj = new Wxobjopen($options);
                    $res = $wxObj->delUserCard($data);
                    if ($res['errcode'] == 0) {
                        $datas['is_del'] = 2;
                        $map['card_id'] = $card_id;
                        $CardGeneral->save($datas, $map);
                        $CardUserGet->save($datas, $map);
                        $CardConsum->save($datas, $map);
                        $rarr['code'] = 0;
                        $rarr['message'] = '删除成功';
                    } else {
                        //错误提示翻译
                        $Helpinfo = new Helpinfo();
                        $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                        //END
                        $rarr['code'] = $res['errcode'];
                        $rarr['message'] = '删除失败'.$errmsg;
                    }
                }else{
                    $rarr['code'] = 9006;
                    $rarr['message'] = '删除失败,此卡券有未被核销的用户，清核销完成后再删除。';
                }
            }else{
                $rarr['code'] = 9007;
                $rarr['message'] = '删除失败,请删除只属于您的卡券';
            }
            return json($rarr);
        }

    }

    //删除草稿
    public function deldrafts(){
        if (Request()->isGet()) {
            $map['id'] = request()->param('id');
            $CardGeneral = new CardGeneral();
            $res = $CardGeneral->where($map)->delete();
            if ($res){
                $this->success('删除成功', 'cards/draftslist','', 1);
            }else{
                $this->error('删除失败', 'cards/draftslist','', 1);
            }
        }
    }

    //详情
    public function infocards($id){
        $CardGeneral = new CardGeneral();
        $info = $CardGeneral->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //详情
    public function getinfocards(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardGeneral = new CardGeneral();
            $info = $CardGeneral->where('id',$arr['id'])->find();
            $info['card_type'] = getcardtype($info['card_type']);
            $info['base_info'] = json_decode($info['base_info'],true);
            if ($info['base_info']['date_info']['type'] == 'DATE_TYPE_FIX_TIME_RANGE') {
                $info['begin_timestamp'] = date('Y-m-d', $info['base_info']['date_info']['begin_timestamp']);
                $info['end_timestamp'] = date('Y-m-d', $info['base_info']['date_info']['end_timestamp']);
            }else{
                $info['begin_timestamp'] = '';
                $info['end_timestamp'] = '';
                $info['fixed_term'] = $info['base_info']['date_info']['fixed_term'];
            }
            $info['statu'] = $info['statu'] == 0 ? '正常' : '异常';
            return json($info);
        }
    }

    //卡券详情
    public function getcardsinfo(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardGeneral = new CardGeneral();
            $info = $CardGeneral->where('card_id', $arr['card_id'])->find();
            $info['logo_url'] = $info['logo_url'];
            $info['title'] =  $info['title'];
//            $info['begin_timestamp'] = date('Y-m-d', $info['base_info']['date_info']['begin_timestamp']);
//            $info['end_timestamp'] = date('Y-m-d', $info['base_info']['date_info']['end_timestamp']);
            $info['statu'] = $info['statu'] == 0 ? '正常' : '异常';
            return json($info);
        }
    }
    //卡券列表(积分商城)
    public function get_cards(){
        $top_mid = Session::get('login_top_mid');
        $mid = $this->get_mer_mid();
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        }else{
            $map['top_mid'] = $top_mid;
        }
        $map['end_timestamp'] = ['gt',time()];
        $map['is_put'] = 1;
        $CardGeneral = new CardGeneral();
        $list = $CardGeneral->where($map)->select();
        return json($list);
    }
    //领取
    public function cardgetlist($card_id = ''){
        $p_data = request()->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['code'] !== '') {
                $map['code'] = $p_data['code'];
            } else {
                $p_data['code'] = '';
            }
            if ($p_data['statu'] !== '') {
                $map['statu'] = $p_data['statu'];
            } else {
                $p_data['statu'] = '';
            }
        } else {
            $p_data['statu'] = '';
            $p_data['code'] = '';
        }
        if ($card_id !== ''){
            $map['card_id'] = $card_id;
        }
        $CardUserGet = new CardUserGet();
        $Merchant = new Merchant();
        $map['card_type'] = ['neq','MEMBER_CARD'];
        $map['is_del'] = 1;
        $mab['id']=array('in',$this->get_mer_mid());
        $mach = $Merchant->where($mab)->order('id desc')->paginate('10');
        $list = $CardUserGet->where($map)->order('id desc')->paginate('20',false,['query' => request()->param()]);
        $card['card_id'] = $card_id;
        $user = Session::get('user');
        $this->assign('p_data',$p_data);
        $this->assign('card',$card);
        $this->assign('list',$list);
        $this->assign('mach',$mach);
        $this->assign('user',$user);
        return $this->fetch();
    }

    //领取列表
    public function cardgetlists($card_id = ''){
        $request = request();
        if ($request->isAjax()) {
            $param = $request->post();
            if (!empty($param['code'])) {
                $map['a.code'] = $param['code'];
            }
            if ($param['statu'] === '0'){
                $map['a.statu'] = 0;
            }else{
                if (!empty($param['statu'])) {
                    $map['a.statu'] = $param['statu'];
                }
            }
            $CardUserGet = new CardUserGet();
            $map['a.card_type'] = ['neq', 'MEMBER_CARD'];
            $map['a.mid'] = array('in', $this->get_mer_mid());
            $map['a.is_del'] = 1;
            if ($param['type'] == "search") {
                $list = $CardUserGet->alias('a')
                    ->join('wn_card_general b', 'a.card_id=b.card_id', 'left')
                    ->join('wn_card_fans c', 'a.openid=c.openid', 'left')
                    ->where($map)
                    ->order('create_time desc')
                    ->field('a.id,a.mid,a.card_type,a.have,a.end_time,a.statu,a.card_id,a.code,a.openid,a.create_time,b.title as card_title,c.nickname')
                    ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])
                    ->select();
                $list2 = [];
                foreach ($list as $k=>$v){
                    $list2[$k] = $v;
                    $list2[$k]['card_type'] = getcardtype($v['card_type']);
                    $list2[$k]['statu'] = $v['statu'] == 2?'已核销':'未核销';
                    $list2[$k]['have'] = $v['have'] == 1?'正常':'已删除';
                    $list2[$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
                }
                unset($map['c.nickname']);
                $re_param["total"] = $CardUserGet->alias('a')->where($map)->count('a.id');
                //获取的记录
                $re_param["rows"] = $list2;
                return json($re_param);
            }elseif ($param['type'] == "out_excel") {

            }
        }else {
            $param = $request->param();
            if (isset($param['card_id'])){
                $card['card_id'] = $param['card_id'];
            }else{
                $card['card_id'] = '';
            }
            $Merchant = new Merchant();
            $mab['id'] = array('in', $this->get_mer_mid());
            $mach = $Merchant->where($mab)->select();
//            $card['card_id'] = $card_id;
            $user = Session::get('user');
            $this->assign('card', $card);
            $this->assign('mach', $mach);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    //获取二维码
    public function getdqrcode($card_id){
        //发送数据
        $data = [
            "action_name"=>"QR_CARD",
            "action_info"=> [
                "card"=> [
                    "card_id" => $card_id,
                    "outer_str" => 'SHOP_PUT',
                ],
            ]
        ];
        //微信
        $mid = $this->getmid($card_id);
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->cardQrcode($data);
        if($res['errcode'] == 0){
            $CardGeneral = new CardGeneral();
            $date['qrcode_url'] = $res['show_qrcode_url'];
            $resu = $CardGeneral->save($date,['card_id'=>$card_id]);
            if ($resu == false) {
                $this->error('更新失败', 'cards/cardslist', '', 1);
            } else {
                $this->success('获取成功', 'cards/cardslist', '', 1);
            }
        }else{
            //错误提示翻译
            $Helpinfo = new Helpinfo();
            $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
            //END
            $this->error('获取失败'.$errmsg, 'cards/cardslist', '', 20);
        }
    }

    //核销状态
    public function consumestatu($card_id,$code){
        $data = [
            'card_id' => $card_id,
            'code' => $code,
            'check_consume' => true
        ];
        $mid = $this->getmid($card_id);
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->getCardState($data);

        if ($res['errcode'] == 0){
            return '0';
        }else{
            return '1';
        }
    }

    //高级设置
    public function senseting(){
        if (Request()->isPost()){
            $arr = request()->post();
            $CardGel = new CardGeneral();
            $map['card_id'] = request()->param('card_id');
            $data['is_dedu_cards'] = $arr['is_dedu_cards'];
            $data['is_dedu_cards_pile'] = $arr['is_dedu_cards_pile'];
            $res = $CardGel->save($data,$map);
            if ($res){
                $this->success('设置成功',url('cards/cardslist',['card_id'=>$map['card_id']]));
            }else{
                $this->error('设置失败',url('cards/cardslist',['card_id'=>$map['card_id']]));
            }
        }else{
            $arr = request()->param();
            $CardGel = new CardGeneral();
            $map['card_id'] = $arr['card_id'];
            $info = $CardGel->where($map)->find();
            $this->assign('card',$info);
            return $this->fetch();
        }
    }

    //卡券核销
    public function cardconsumes(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $Helpinfo = new Helpinfo();
            $info = $CardUserGet->where('id',$arr['id'])->find();
            $statu = $this->consumestatu($info['card_id'],$info['code']);
            if ($statu == 0){
                //核销状态正常
                $data = [
                    'code' => $info['code'],
                    'card_id' => $info['card_id'],
                ];
//                $mid = $this->getmid($info['card_id']);
                $options = $this->options($info['card_id']);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->consumeCode($data);
//                return json($res);
                if ($res['errcode'] == 0){
                    $CardConsume = new CardConsume();
                    $CardGeneral = new CardGeneral();
                    //款台
                    $datac['kuantai'] = 'web';
                    $datac['source'] = 'web';
                    $datac['code'] = $info['code'];
                    $datac['card_id'] = $info['card_id'];
                    $datac['openid'] = $info['openid'];
                    $datac['mid'] = $arr['mid'];
                    $datac['con_username'] = $arr['nickname'];
                    $datac['action_user'] = $arr['nickname'];
                    $datac['mode'] = 1;
                    $datac['hx_fs'] = 'web';
                    $datac['create_time'] = time();
                    $CardConsume->save($datac);
                    $CardUserGet->save(['statu'=>2],['id'=>$arr['id']]);
                    $CardGeneral->where('card_id',$info['card_id'])->setInc('consume');
                    $datar['code'] = 0;
                    $datar['message'] = '核销成功！';
                    return json($datar);
                }else{
                    //错误提示翻译

                    $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                    //END
                    $datar['code'] = 9001;
                    $datar['message'] = '核销失败！'.$errmsg;
                    return json($datar);
                }
            }else{

                //核销状态异常
                $datar['code'] = 9002;
                $datar['message'] = '核销状态异常！';
                return json($datar);
            }
        }
    }

    //核销记录
    public function consumelist(){
        $CardConsume = new CardConsume();
        $list = $CardConsume->where('statu',0)->paginate(20);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //检查可领取次数
    public function checkcardsgetsume(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            return json($arr);
            if ($arr['pval'] !=='' && $arr['sval'] !=='') {
                $cardget =getcardgetsume($arr['sval']);
                $zs_no = (int)$arr['pval'];
                if ($zs_no > $cardget) {
                    $rarr['get_sume'] = $cardget;
                    $rarr['code'] = '9001';
                    $rarr['message'] = '超过了该卡券可领取数量';
                } else {
                    $rarr['get_sume'] = $cardget;
                    $rarr['code'] = '0';
                    $rarr['message'] = '正常';
                }
            }else{
                $rarr['get_sume'] = '';
                $rarr['code'] = '9006';
                $rarr['message'] = '请选择卡券并输入数量';
            }
            return json($rarr);
        }
    }

    //获取卡券列表(充送
    public function getgivecard(){
        if (Request()->isAjax()) {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
//            $mab['end_timestamp'] = ['gt', time()];
            $mab['is_cgive'] = 1;
            $cards = $CardGeneral->where($mab)->order('id desc')->field('card_id,title,get_limit')->select();
            $cardlist = [];
            foreach ($cards as $k=>$v) {
                if (filtergqcard($v['card_id'] == true)){
                    $cardlist[$k]['title'] = $v['title'];
                    $cardlist[$k]['card_id'] = $v['card_id'];
                    $cardlist[$k]['get_limit'] = getcardgetsume($v['card_id']);
                }
            }
            if ($cardlist) {
                $arr = ['code' => 0, 'message' => 'success', 'data' => $cardlist,'sql'=>$CardGeneral->getLastSql()];
            } else {
                $arr = ['code' => 0, 'message' => 'error','sql'=>$CardGeneral->getLastSql()];
            }
            return json($arr);
        }
    }

    //获取卡券列表
    public function getcardlist(){
        if (Request()->isAjax()) {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
//            $mab['end_timestamp'] = ['gt', time()];
            $mab['is_put'] = 1;
            $cards = $CardGeneral->where($mab)->order('id desc')->field('card_id,title,get_limit')->select();
            $cardlist = [];
            foreach ($cards as $k=>$v) {
                if (filtergqcard($v['card_id'] == true)){
                    $cardlist[$k]['title'] = $v['title'];
                    $cardlist[$k]['card_id'] = $v['card_id'];
                    $cardlist[$k]['get_limit'] = getcardgetsume($v['card_id']);
                }
            }
            if ($cardlist) {
                $arr = ['code' => 0, 'message' => 'success', 'data' => $cards,'sql'=>$CardGeneral->getLastSql()];
            } else {
                $arr = ['code' => 0, 'message' => 'error','sql'=>$CardGeneral->getLastSql()];
            }
            return json($arr);
        }
    }

    //获取卡券列表
    public function getpaycard(){
        if (Request()->isAjax()) {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['is_pay'] = 1;
            $mab['is_put'] = 1;
            $mab['end_timestamp'] = ['gt', time()];
            $cards = $CardGeneral->where($mab)->field('card_id,title')->select();
            foreach ($cards as $k=>$v){
                $cardlist[$k]['title'] = $v['title'];
                $cardlist[$k]['card_id'] = $v['card_id'];
                $cardlist[$k]['get_limit'] = getcardgetsume($v['card_id']);
            }
            if ($cardlist) {
                $arr = ['code' => 0, 'message' => 'success', 'data' => $cardlist];
            } else {
                $arr = ['code' => 0, 'message' => 'error'];
            }
            return json($arr);
        }
    }

    //获取卡券列表 (免费券)
    public function getfreecard(){
        if (Request()->isAjax()) {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['is_pay'] = 0;
            $mab['is_put'] = 1;
            $mab['end_timestamp'] = ['gt', time()];
            $cards = $CardGeneral->where($mab)->field('card_id,title')->select();
            foreach ($cards as $k=>$v){
                $cardlist[$k]['title'] = $v['title'];
                $cardlist[$k]['card_id'] = $v['card_id'];
                $cardlist[$k]['get_limit'] = getcardgetsume($v['card_id']);
            }
            if ($cardlist) {
                $arr = ['code' => 0, 'message' => 'success', 'data' => $cardlist];
            } else {
                $arr = ['code' => 0, 'message' => 'error'];
            }
            return json($arr);
        }
    }

    public function getcardlists(){
        if (Request()->isAjax()) {
            $CardCzgive = new CardCzgive();
            $arr = request()->post();
            $give = $CardCzgive->where(['id'=>$arr['id']])->find();
            $zs_card_id_all = json_decode($give['zs_card_id_all'],JSON_UNESCAPED_UNICODE);
            $CardGeneral = new CardGeneral();
            foreach ($zs_card_id_all as $k=>$v){
                $cardlist[$k]['title'] = $CardGeneral->where(['card_id'=>$v['zs_card_id'],'is_put'=>1])->value('title');
                $cardlist[$k]['card_id'] = $v['zs_card_id'];
                $cardlist[$k]['get_limit'] = $v['zs_no'];
            }
            if ($cardlist) {
                $arr = ['code' => 0, 'message' => 'success', 'data' => $cardlist];
            } else {
                $arr = ['code' => 0, 'message' => 'error'];
            }
            return json($arr);
        }
    }



    //设置库存
    public function editstock(){
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $data['card_id'] = $card_id;
                if ($arr['stock'] == 1) {
                    $data['increase_stock_value'] = (int)$arr['stock_number'];
                } else {
                    $data['reduce_stock_value'] = (int)$arr['stock_number'];
                }
                $options = $this->options($card_id);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->cardStock($data);
                if ($res['errcode'] == 0) {
                    $stockadd = (int)$arr['stock_number'];
                    $CardGeneral = new CardGeneral();
                    //增加
                    if ($arr['stock'] == 1) {
                        $CardGeneral->where('card_id', $card_id)->setInc('stocks', $stockadd);
                        //减少
                    } else {
                        $CardGeneral->where('card_id', $card_id)->setDec('stocks', $stockadd);
                    }
                    $this->success('修改成功', url('cards/cardslist', ['card_id' => $card_id]), 1);
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                    //END
                    $this->error('修改失败' . $errmsg, url('cards/cardslist', ['card_id' => $card_id]), 1);
                }
            } else {
                $card['card_id'] = $card_id;
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('请修改属于您的卡券','cards/cardslist');
        }
    }

    //商户ID
    public function getmid($card_id){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id'=>$card_id])->value('mid');
        if (empty($top_mid)){
            $top_mid = $CardGeneral->where(['card_id'=>$card_id])->value('mid');
            return $top_mid;
        }else{
            return $top_mid;
        }
    }

    //微信API参数 根据mid获取
    public function option($mid){
        Session::set('openid', null);
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $Merchant=new Merchant();
        $merchantinfo=$Merchant->where('id',$mid)->field('wx_open_id,agent')->find();
        $mab['id'] =$merchantinfo['wx_open_id'];
        $config =$Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数  根据card_id获取
    public function options($card_id){
        Session::set('openid', null);
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $map['id'] = $CardGeneral->where('card_id',$card_id)->value('mid');
        $merchantinfo= $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $config =$Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


    //修改卡券
//    public function editcards($card_id){
//        $CardGeneral = new CardGeneral();
//        $top_mid = Session::get('login_top_mid');
//        $map['top_mid'] = ['in',$top_mid];
//        $map['card_id'] = $card_id;
//        $map['statu'] = '0';
//        $info = $CardGeneral->where($map)->find();
//        if (Request()->isPost()){
//            $carddate = new Carddate();
//            $arr = request()->post();
//            $data = $carddate->editorcard($arr,1);
//            //初始化微信API
//            $mid = $this->getmid($card_id);
//            $options = $this->option($mid);
//            $wxObj = new Wxobjopen($options);
//            $res = $wxObj->updateUserCard($data);
//            if ($res['errcode'] == 0){
//                $datas = $carddate->editorcard($arr,2);
//                $conten = $CardGeneral->save($datas,['card_id'=>$card_id]);
//                if($conten !== false){
//                    $this->success('创建成功', 'cards/cardslist','', 1);
//                }else{
//                    $this->error('创建失败', 'cards/cardslist','', 1);
//                }
//            }else{
//                //错误提示翻译
//                $Helpinfo = new Helpinfo();
//                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
//                //END
//                $this->error('创建失败'.$errmsg, 'cards/cardslist','', 1);
//            }
//        }else{
//            $this->assign('info',$info);
//            return $this->fetch();
//        }
//    }

}
